/****************************************************
File Name:46-2-client.c
Author: Abby Cin
Mail: abbytsing@gmail.com
Created Time: Thu 11 Sep 2014 08:42:00 PM CST
*****************************************************/
#include"msg.h"
#include<string.h>
#include<fcntl.h>
#include<signal.h>

static int id;

void
dealing (int sig)
{
    if (msgctl (id, IPC_RMID, NULL) == -1)
      err ("msgctl");
    exit (0);
}

int
main (int argc, char *argv[])
{
    if (argc < 2 || strcmp (argv[1], "--help") == 0)
     {
        printf ("%s path\n press 'ctrl' + 'c' to quit\n", argv[0]);
        exit (1);
     }
    struct sigaction act;
    struct msgbuf clientmsg, tmp;
    int client, server;
    int perm = S_IWUSR | S_IRUSR | S_IWGRP;
    
    if (sigemptyset (&act.sa_mask) == -1)
      err ("sigemptyset");
    act.sa_flags = 0;
    act.sa_handler = dealing;
    
    if (sigaction (SIGINT, &act, NULL) == -1)
      err ("sigaction");
    
    server = msgget (key, perm);	// get server msgid
    
    if (server == -1 && errno != EEXIST)
      err ("msgget");
    
    client = msgget (IPC_PRIVATE, perm | IPC_CREAT | IPC_EXCL);	// get client msgid
    id = client;			// get the client msgqid
    if (client == -1 && errno != EEXIST)
        err ("msgget");
    
    clientmsg.mtype = 1;		/* same server and client mtype */
    clientmsg.id = client;	/* send server client msgid */
    
    if (strcpy (clientmsg.mtext, argv[1]) == NULL)	/* contents the path */
        err ("memcpy");
    if (msgsnd (server, (void *) &clientmsg, DATA_SIZE, 0) == -1)	// pathname won't be too long
    {
        if (errno != EAGAIN)
          err ("send path to server");
    }
    
    tmp.mtype = 1;		// a test
    
    for (;;)
    { 
        if (msgrcv (client, (void *) &tmp, DATA_SIZE, 0, 0) == -1)
          err ("msgrcv");
        if (tmp.mtype == 3)
          break;
        printf ("%s", tmp.mtext);
    }
    if (msgctl (client, IPC_RMID, NULL) == -1)
    err ("clean failed");
    
    exit (0);
}

// kate: indent-mode cstyle; indent-width 2; replace-tabs on; 
